<template>
  <div class="page-container">
    <!-- 头部 -->
    <div>
      <el-form ref="form" :model="searchform" inline label-width="80px">
        <el-form-item>
          <el-button @click="addDialog()" type="success" size="small"
            >添加用户</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-tooltip
            effect="dark"
            content="点击进行批量数据的删除"
            placement="top"
          >
            <el-button @click="delBatch()" size="small" type="danger"
              >批量删除</el-button
            >
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchform.name"
            size="small"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="search()" size="small" type="primary"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格部分 -->
    <div>
      <!-- max-height="1000" -->
      <el-table
        ref="reftb"
        v-loading="loading"
        :data="list"
        max-height="550"
        style="width: 100%"
        :row-key="(r) => r.userId"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="用户姓名">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="登录账户">
                <span>{{ props.row.loginName }}</span>
              </el-form-item>
              <el-form-item label="手机号码">
                <span>{{ props.row.phone }}</span>
              </el-form-item>
              <el-form-item label="部门">
                <span>{{ props.row.deptName }}</span>
              </el-form-item>
              <el-form-item label="角色">
                <span>{{ props.row.roleName }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>

        <!-- 复选框列 -->
        <el-table-column
          :reserve-selection="true"
          :selectable="(r) => r.roleId > 1"
          type="selection"
        >
        </el-table-column>

        <el-table-column prop="userId" label="编号" width="60">
        </el-table-column>

        <el-table-column prop="path" label="头像">
          <template slot-scope="scope">
            <el-avatar :size="60">
              <img :src="baseURL + scope.row.path" />
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="姓名"> </el-table-column>

        <el-table-column
          header-align="center"
          align="center"
          prop="loginName"
          label="账户"
        >
        </el-table-column>

        <el-table-column prop="phone" label="手机号码"> </el-table-column>

        <el-table-column sortable prop="sex" label="性别"> </el-table-column>

        <el-table-column prop="roleName" label="角色"> </el-table-column>

        <el-table-column prop="deptName" label="部门"> </el-table-column>

        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-switch
              :disabled="scope.row.roleId == 1"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </template>
        </el-table-column>

        <!-- 自定义组件 操作 -->
        <el-table-column width="200" fixed="right" label="操作">
          <!-- 插槽 -->
          <!--  作用域插槽  -->
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.roleId > 1"
              type="warning"
              @click="updateDialog(scope)"
              size="mini"
              >修改</el-button
            >
            <el-popconfirm
              style="margin-left: 10px"
              confirm-button-text="确定删除"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除此用户信息？"
              @confirm="del(scope)"
              v-if="scope.row.roleId > 1"
            >
              <el-button slot="reference" type="danger" size="mini"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagebox">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- dialog 弹层  添加 修改 -->
    <!-- :before-close="dialogBeforeClose"  弹层关闭事件 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
    >
      <el-card>
        <div>
          <el-form
            ref="refform"
            :rules="rules"
            :model="form"
            label-width="80px"
            :gutter="20"
            inline
          >
            <!-- 布局  -->
            <el-row :gutter="20">
              <el-col :sm="24" :md="12"></el-col>
              <el-col :sm="24" :md="12"></el-col>
            </el-row>
            <!-- 头像  -->
            <el-row :gutter="20">
              <el-col :sm="24" :md="12">
                <el-form-item
                  v-if="dialogUpdate"
                  prop="userId"
                  label="用户编号"
                  size="small"
                >
                  <el-input v-model="form.userId" disabled>
                    <i slot="suffix" class="el-icon-s-release"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="name" label="用户姓名" size="small">
                  <el-input
                    v-model="form.name"
                    maxlength="10"
                    clearable
                    placeholder="请输入姓名"
                  ></el-input>
                </el-form-item>

                <el-form-item prop="sex" label="性别" size="small">
                  <el-radio-group v-model="form.sex">
                    <el-radio-button label="男"></el-radio-button>
                    <el-radio-button label="女"></el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item prop="phone" label="手机号码" size="small">
                  <el-input
                    clearable
                    v-model="form.phone"
                    maxlength="11"
                    show-word-limit
                    placeholder="请输入手机号码"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12">
                <el-form-item label="头像">
                  <input type="hidden" v-model="form.imgId" />
                  <el-upload
                    class="avatar-uploader"
                    :action="imgUploadURL"
                    name="file"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.path" :src="form.path" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 账户 密码 -->
            <el-row :gutter="20">
              <el-col :sm="24" :md="12">
                <el-form-item prop="loginName" label="用户账户" size="small">
                  <el-input
                    clearable
                    v-model="form.loginName"
                    placeholder="请输入账户"
                  >
                    <!-- slot 插槽 -->
                    <!-- <i slot="prefix" class="el-icon-user"></i> -->
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12">
                <el-form-item
                  v-if="!dialogUpdate"
                  prop="loginPwd"
                  label="登录密码"
                  size="small"
                >
                  <el-input
                    clearable
                    v-model="form.loginPwd"
                    show-password
                    placeholder="请输入密码"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 部门 角色  -->
            <el-row :gutter="20">
              <el-col :sm="24" :md="12">
                <el-form-item prop="deptId" label="部门" size="small">
                  <el-select v-model="form.deptId" placeholder="请选择部门">
                    <el-option
                      v-for="item in depts"
                      :key="item.deptId"
                      :label="item.deptName"
                      :value="item.deptId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12">
                <el-form-item   prop="roleId" label="角色" size="small">
                  <el-select v-model="form.roleId" @change="$forceUpdate()" placeholder="请先选择部门">
                    <el-option
                      v-for="item in roles"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 状态  -->
            <el-row :gutter="20">
              <el-col :sm="24" :md="12">
                <el-form-item label="状态" size="small">
                  <el-switch
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="正常"
                    inactive-text="冻结"
                    v-model="form.status"
                  ></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="12"></el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>

      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!dialogUpdate" type="primary" @click="addSave()"
          >添 加</el-button
        >
        <el-button v-if="dialogUpdate" type="primary" @click="updateSave()"
          >修 改</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Template from "../Intervene/Template.vue";
export default {
  components: { Template },
  data() {
    return {
      loading: true,
      dialogVisible: false,
      dialogTitle: "添加用户",
      dialogUpdate: false,
      url: "/api/Users",
      depts: [],
      

      list: [],
      total: 0,
      pageSize: 5,
      pageIndex: 1,

      searchform: {
        name: "",
      },
      baseURL: axios.defaults.baseURL,
      imgUploadURL: axios.defaults.baseURL + "/api/Upload",
      imageUrl: "",
      form: {},
      //表单验证规则
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3|4|5|7|8|6|9][0-9]\d{8}$/,
            message: "手机号码格式错误",
            trigger: ["blur"],   //, "change"
          },
        ],
        loginName: [{ required: true, message: "请输入账户", trigger: "blur" }],
        loginPwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
        deptId: [{ required: true, message: "请选择部门", trigger: "blur" }],
        roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
      },
    };
  },
  computed: {
    //角色处理
    roles(){
      if(!this.form.deptId)
      return [];
      let roles = this.depts.filter(v=>v.deptId==this.form.deptId)[0].roles;
      if (!roles.some(v=>v.roleId==this.form.roleId))
      this.form.roleId = roles[0].roleId;
      this.$forceUpdate();
      return this.depts.filter(v=>v.deptId==this.form.deptId)[0].roles;
    }
  },
  methods: {
    //添加弹层
    addDialog() {
      this.dialogUpdate = false;
      this.dialogVisible = true;
      this.dialogTitle = "添加用户";
      this.form = {
        sex: "男",
        imgId: 4,
        status: true,
        path: this.baseURL + "/Files/HeadImg/user.png",
      }; //清空数据
    },
    //添加保存
    addSave() {
      //console.log(this.form);
      //先判断验证是否通过  refform 是form 上 ref 的值
      this.$refs.refform.validate((v) => {
        if (v) {
          this.axios({
            method: "post",
            url: this.url,
            data: this.form,
          })
            .then((response) => {
              //console.log(response.data);
              if(response.data.code>0){
                this.dialogVisible = false;
                this.$message.success(response.data.msg);
                this.getList(); //刷新数据
              }else{
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              console.log(error);
              this.$message.error("添加异常！");
            });
          //this.$message.success("添加成功！");
        } else {
          this.$message.error('请按要求输入数据！');
        }
      });
    },

    //修改弹层
    updateDialog(scope) {
      //console.log("scope: ", scope.row);
      this.dialogUpdate = true;
      this.dialogVisible = true;
      this.dialogTitle = "修改用户";
      //console.log(scope.row);
      this.form = JSON.parse(JSON.stringify(scope.row)); // 将行数据赋值给 表单
      this.form.path = this.baseURL + this.form.path;
    },
    //修改保存
    updateSave() {
      //console.log(this.form);
      //先判断验证是否通过  refform 是form 上 ref 的值
      this.$refs.refform.validate((v) => {
        if (v) {
          this.axios({
            method: "put",
            url: this.url+ "/" + this.form.userId,
            data: this.form,
          })
            .then((response) => {
              //console.log(response.data);
              if(response.data.code>0){
                this.dialogVisible = false;
                this.$message.success(response.data.msg);
                this.getList(); //刷新数据
              }else{
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              console.log(error);
              this.$message.error("修改异常！");
            });
          //this.$message.success("修改成功！");
        } else {
          this.$message.error('请按要求输入数据！');
        }
      });
    },

    //删除
    del(scope) {
      //console.log("emID: ", scope.row.emID);
      this.axios({
        method: "delete",
        url: this.url + "/" + scope.row.userId,
      })
        .then((response) => {
          //console.log(response.data);
          if (response.data.code > 0) {
            this.$message.success(response.data.msg);
            this.getList();
          } else {
            this.$message.error(response.data.msg);
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("删除异常");
        });
    },
    //批量删除
    delBatch() {
      //获取选中行数据
      // 父组件通过 ref 属性获取子组件中的 数据
      //console.log(this.$refs.reftb.selection);
      let selection = this.$refs.reftb.selection;
      if (selection.length < 1) {
        this.$message.warning("请先选择要删除的用户");
        return;
      }
      let names = selection.map((v) => v.name);
      this.$confirm(
        "此操作将永久删除[" + names + "]的用户信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let ids = selection.map((v) => v.userId);
          //console.log(ids);
          //删除代码  axios
          this.axios({
            method: "delete",
            url: this.url + "/batch",
            data: ids,
          })
            .then((response) => {
              //console.log(response.data);
              if (response.data.code > 0) {
                this.$message.success(response.data.msg);
                this.getList();
                this.$refs.reftb.clearSelection(); //清除已经删除的选中效果
              } else {
                this.$message.error(response.data.msg);
              }
            })
            .catch((error) => {
              console.log(error);
              this.$message.error("删除异常");
            });
        })
        .catch(() => {
          this.$message("已取消删除");
        });
    },

    //搜索
    search() {
      this.pageIndex = 1;
      this.getList();
    },
    //GET 请求获取数据
    getList() {
      this.loading = true;
      axios({
        method: "get", //请求方式,
        url: this.url,
        //post 的参数放入 data 中
        params: {
          size: this.pageSize,
          page: this.pageIndex,
          name: this.searchform.name,
        },
      })
        .then(response => {
          //console.log(response.data);
          //将获取到的数据更新到 list 中
          this.list = response.data.list;
          this.total = response.data.count;
          this.pageIndex = response.data.page;
          this.pageSize = response.data.size;
          setTimeout(() => {
            this.loading = false;
          }, 333);
        })
        .catch(error=> {
          console.log(error);
        });
    },
    //翻页
    handleCurrentChange(page) {
      this.pageIndex = page;
      this.getList();
    },
    //每页显示数量的改变
    handleSizeChange(size) {
      this.pageSize = size;
      this.getList();
    },

    //开始上传
    beforeAvatarUpload(file) {
      //console.log("file: ", file);
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //上传成功回调
    handleAvatarSuccess(res, file) {
      //console.log("res, file: ", res, file);
      if (res.code == 1) {
        this.form.imgId = res.imgID;
        this.form.path = this.baseURL + res.path;
        //console.log("this.form.path: ", this.form.path);
      } else {
        this.$message.error(res.msg);
      }
    },
    //获取组织结构 部门+角色
    getOrganization(){
      this.axios({
        method: "get", //请求方式,
        url: "/api/Organization",
      })
        .then((response) => {
          //console.log(response.data);
          //将获取到的数据更新
          if(response.data.code==1){
            this.depts = response.data.data;
          }else{
            this.$message.warning("组织数据加载失败！");
          }
        })
        .catch(error=>{
          console.log(error);
        });
    },
  },
  created() {
    this.getList();
    this.getOrganization();
  },
};
</script>

<style>
.pagebox {
  text-align: center;
  padding: 10px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>